package tech.abing.spider.task.pipeline;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import tech.abing.spider.component.Pipeline;
import tech.abing.spider.model.Proccessable;
import tech.abing.spider.task.model.RateInfo;
import tech.abing.spider.util.ProccessableUtil;
import tech.abing.spider.util.SqlUtil;

public class RatePipeline implements Pipeline {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(RatePipeline.class);
	private static SqlUtil sqlUtil = null;
	
	public RatePipeline() {
		
		if(sqlUtil == null){
			//创建数据库链接
			sqlUtil = SqlUtil.getInstance();
			logger.info("数据库连接创建成功！");
		}
	}
	
	
	@Override
	public void proccessData(List<Proccessable> objectContainer) {

		if (ProccessableUtil.instanceOfClass(objectContainer, RateInfo.class)) {// 判断集合类型是否是XiciProxy
			List<RateInfo> list = ProccessableUtil.convert(objectContainer, RateInfo.class);// 转换
			String querySql = "select count(*) from tbdaily.tb_shop_rate where shop_id=?";
			String insertSql = "insert into tbdaily.tb_shop_rate(id,shop_id,item_id,type,sale_count) values(?,?,?,?,?)";
			String updateSql = "update tbdaily.tb_shop_rate set ";
			for (RateInfo ri : list) {
				Map<String, Object> map = sqlUtil.searchForConn(querySql, ri.getShopId());
				if(map != null && !map.isEmpty()){
					sqlUtil.updateForConn(updateSql, "");
				}else{
					sqlUtil.insertForConn(insertSql, "");
				}
			}
		}

	}

	@Override
	public void destory() {
		sqlUtil.closeConn();
		logger.info("数据库连接关闭成功！");
	}

}
